﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Bpms.Data;
using Bpms.Entity;
using Bpms.Log;
using Bpms.Cache;

namespace Bpms.Bll
{
    /// <summary>
    /// 用户逻辑操作类
    /// </summary>
    public class User
    {
        #region Member

        /// <summary>
        /// 数据库改动事件委托
        /// </summary>
        public delegate void DBChangedEventHandler();

        /// <summary>
        /// 日志事件委托
        /// </summary>
        public delegate void LogEventHandler();

        /// <summary>
        /// 数据库改动事件
        /// </summary>
        public static event DBChangedEventHandler DBChanged;

        /// <summary>
        /// 写日志事件
        /// </summary>
        public static event LogEventHandler WriteLog;

        #region Private

        private static IDataProvider provider = DatabaseProvider.GetInstance();

        /// <summary>
        /// 数据改动事件处理函数
        /// </summary>
        static void OnDBChanged()
        {
            if (DBChanged != null)
            {
                DBChanged();
            }
        }

        /// <summary>
        /// 写日志处理函数
        /// </summary>
        static void OnWriteLog()
        {
            if (WriteLog != null)
            {
                WriteLog();
            }
        }

        #endregion

        #endregion

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="user">用户实体对象</param>
        /// <returns>-1：记录已经存在（存在同名的E-mail），0：失败，1：成功</returns>
        public static int InsertUser(UserInfo user)
        {
            if (provider.UserExists(user, OperateType.Insert))
            {
                return -1;
            }
            if (provider.InsertUser(user))
            {
                OnDBChanged();
                OnWriteLog();
                return 1;
            }

            return 0;
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="user">用户实例</param>
        /// <returns>-1：记录已经存在（存在同名的E-mail），0：失败，1：成功</returns>
        public static int UpdateUser(UserInfo user)
        {
            if (provider.UserExists(user, OperateType.Update))
            {
                return -1;
            }
            if (provider.UpdateUser(user))
            {
                OnDBChanged();
                OnWriteLog();
                return 1;
            }

            return 0;
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userId">用户的UserID</param>
        /// <returns>操作是否成功（true：成功，false：失败）</returns>
        public static bool DeleteUser(int userId)
        {
            if (provider.DeleteUser(userId))
            {
                OnDBChanged();
                OnWriteLog();
                return true;
            }

            return false;
        }

        /// <summary>
        /// 判断用户是否存在
        /// </summary>
        /// <param name="user">用户实体对象</param>
        /// <param name="type">判断的类型（添加或修改）</param>
        /// <returns>用户是否存在（true：已存在，false：未存在）</returns>
        public static bool UserExists(UserInfo user, OperateType type)
        {
            return provider.UserExists(user, type);
        }

        /// <summary>
        /// 得到用户的基本信息
        /// </summary>
        /// <param name="userId">用户的UserID</param>
        /// <returns>用户实体对象</returns>
        public static UserInfo GetUser(int userId)
        {
            return provider.GetUser(userId);
        }

        /// <summary>
        /// 得到用户的基本信息
        /// </summary>
        /// <param name="email">用户的E-mail（用户名）</param>
        /// <returns>用户实体对象</returns>
        public static UserInfo GetUser(string email)
        {
            return provider.GetUser(email);
        }

        /// <summary>
        /// 提取用户列表
        /// </summary>
        /// <param name="pageId">当前页</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="condition">提取条件</param>
        /// <returns>用户列表</returns>
        public static IList<UserInfo> GetUsers(int pageId, int pageSize, string condition)
        {
            IList<UserInfo> users = null;

            CacheContext cache = CacheContext.GetCacheService(new DefaultCache());

            if (pageId == 1)
            {
                users = cache.RetrieveObject(Cache.CacheKey.UserList.ToString()) as IList<UserInfo>;
                if (users == null)
                {
                    users = provider.GetUsers(pageId, pageSize, condition);
                    cache.AddObject(Cache.CacheKey.UserList.ToString(), users);
                }
            }
            else
            {
                users = provider.GetUsers(pageId, pageSize, condition);
            }

            return users;
        }

        /// <summary>
        /// 得到满足条件的记录数
        /// </summary>
        /// <param name="condition">条件</param>
        /// <returns>满足条件的记录数</returns>
        public static int GetUserCount(string condition)
        {
            return provider.GetUserCount(condition);
        }

        /// <summary>
        /// 验证用户登录
        /// </summary>
        /// <param name="UserInfo">用户实体类</param>
        /// <returns>-2：用户名不存在；-1：密码错误（用户名存在），0：用户处于注销状态（用户名和密码正确），1：登录成功</returns>
        public static int VerifyUser(ref UserInfo user)
        {
            if (!provider.UserExists(user, OperateType.Insert))
            {   // 判断用户名是存在（-2表示用户名不存在）
                return -2;
            }

            if (provider.VerifyUser(ref user))
            {   // 若用户名存在，验证密码是否正确
                if (user.IsEnabled == 1)
                {   // 检查用户的状态（0：注销，1：启动），只有启动状态的才可以登录
                    return 1;
                }
                else
                {   // 登录失败（用户名和密码正确，但用户处于注销状态）
                    return 0;
                }
            }
            else
            {   // 登录失败（密码不正确）
                return -1;
            }
        }

        /// <summary>
        /// 启动一个用户
        /// </summary>
        /// <param name="userId">用户的UserID</param>
        /// <returns>操作是否成功，true：成功，false：失败</returns>
        public static bool StartUser(int userId)
        {
            if (provider.StartUser(userId))
            {
                OnDBChanged();
                OnWriteLog();
                return true;
            }

            return false;
        }

        /// <summary>
        /// 注销一个用户
        /// </summary>
        /// <param name="userId">用户的UserID</param>
        /// <returns>操作是否成功，true：成功，false：失败</returns>
        public static bool CancelUser(int userId)
        {
            if (provider.CancelUser(userId))
            {
                OnDBChanged();
                OnWriteLog();
                return true;
            }

            return false;
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="userId">用户的UserID</param>
        /// <param name="newPassword">新密码</param>
        /// <returns>操作是否成功，true：成功，fales：失败</returns>
        public static bool UpdatePassword(int userId, string newPassword)
        {
            if (provider.UpdatePassword(userId, newPassword))
            {
                OnDBChanged();
                OnWriteLog();
                return true;
            }

            return false;
        }

        /// <summary>
        /// 为用户分配客户
        /// </summary>
        /// <param name="userId">用户的UserID</param>
        /// <param name="customerIdString">客户的CustomerID数组</param>
        /// <returns>操作是否成功（true：成功，false：失败）</returns>
        public static bool DistributeCustomer(int userId, string[] customerIdList)
        {
            if (provider.DistributeCustomer(userId, customerIdList))
            {
                OnDBChanged();
                OnWriteLog();
                return true;
            }

            return false;
        }

        /// <summary>
        /// 判断是否为用户分配了某一客户
        /// </summary>
        /// <param name="customers">为该用户分配的客户集合</param>
        /// <param name="customerId">某一客户ID</param>
        /// <returns>是否分配（true：已分配，false：未分配）</returns>
        public static bool IsContainsCustomer(IList<CustomerInfo> customers, int customerId)
        {
            return provider.IsContainsCustomer(customers, customerId);
        }

        /// <summary>
        /// 设置用户角色
        /// </summary>
        /// <param name="userId">用户的UserID</param>
        /// <param name="roleId">角色ID</param>
        /// <returns>操作是否成功（true：成功，false：失败）</returns>
        public static bool SetRole(int userId, int roleId)
        {
            return provider.SetRole(userId, roleId);
        }

        /// <summary>
        /// 根据用户的UserID，得到E-mail（用户名）
        /// </summary>
        /// <param name="userId">用户的UserID</param>
        /// <returns>用户的用户名</returns>
        public static string GetEmailByUserID(int userId)
        {
            return provider.GetEmailByUserID(userId);
        }

        /// <summary>
        /// 根据用户的E-mail（用户名），得到UserID
        /// </summary>
        /// <param name="email">用户的E-mail</param>
        /// <returns>用户的用户名</returns>
        public static int GetUserIDByEmail(string email)
        {
            return provider.GetUserIDByEmail(email);
        }
    }
}
